<?php

class UserCate extends AppModel {

    var $name = 'UserCate';
    
    // 用户模块不能使用tree结构，用户新增数据太多，不适合左右节点大量的修改值，性能太低。
    // var $actsAs = array('Tree'=> array('left'=>'left','right'=>'right') );
    /**
     * 
     * @param unknown $model	模块
     * @param unknown $user_id	用户编号
     * @param string $without 不包含的id，为数值或者数组
     * @param string $with_third	是否包含3级分类
     * @return Ambigous <string, multitype:string >
     */
    public function getCateList($model,$user_id,$without='',$with_third = false){
    	
    	$model_cates = $this->find('all',array(
    			'conditions'=>array(
    					'creator'=> $user_id,
    					'model'=> $model,
    			),
    			'order' => 'parent_id desc',
    			'fields' =>'id,name,parent_id',
    	));
    	$cates = $parents = array();
    	foreach($model_cates as $cate) {
    		$cates[$cate['UserCate']['parent_id']][] = $cate;
    	}
    	$parents = array(''=>'==请选择==');
    	if(!empty($cates[''])) {
    		foreach ($cates[''] as $cate) {
    			if(is_array($without) && in_array($cate['UserCate']['id'],$without) || $without == $cate['UserCate']['id']) {
    				continue;
    			}
    			$parents[$cate['UserCate']['id']] = $cate['UserCate']['name'];
    			if(isset($cates[$cate['UserCate']['id']]) ) {
    				foreach($cates[$cate['UserCate']['id']] as $subcate){
    					if(is_array($without) && in_array($subcate['UserCate']['id'],$without) || $without == $subcate['UserCate']['id']) {
    						continue;
    					}
    					$parents[$subcate['UserCate']['id']] = "▷ ▷ ▷ ".$subcate['UserCate']['name'];
    					// 上级分类最多两级可选。
    					if($with_third){
    					    if(isset($cates[$subcate['UserCate']['id']]) ) {
    					    	foreach($cates[$subcate['UserCate']['id']] as $thridcate){
    					    		$parents[$thridcate['UserCate']['id']] = "▷ ▷ ▷ ▷ ▷ ▷ ▷ ".$thridcate['UserCate']['name'];
    					    	}
    					    }
    					}
    				}
    			}
    		}
    	}
    	return $parents;
    }
    
    public function getModelCates($model,$user_id){
        
        $cache_key = 'model_cate_'.$model.'_'.$user_id;
        $model_cates = Cache::read($cache_key);
        if($model_cates === false) {
            $model_cates = $this->find('all',array(
                'conditions'=>array(
                    'creator'=> $user_id,
                    'model'=> $model,
                ),
                'order' => 'parent_id desc,id asc',
            ));
            Cache::write($cache_key,$model_cates,'default',60);
        }
        return $model_cates;
    }

}
?>